package com.gaogzhen.algorithm.leetCode;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class Intersect {
    public static void main(String[] args) {
        int[] n1 = {1, 2, 2, 1, 5, 5, 555};
        int[] n2 = {1, 2, 5, 5, 555};
        System.out.println(Arrays.toString(intersect(n1, n2)));

    }

    public static int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map1 = new HashMap<>();
        Map<Integer, Integer> map2 = new HashMap<>();
        Map<Integer, Integer> map3 = new HashMap<>();
        for (int n1 : nums1) {
            map1.put(n1, map1.containsKey(n1) ? map1.get(n1) + 1 : 1);
        }
        for (int n2 : nums2) {
            map2.put(n2, map2.containsKey(n2) ? map2.get(n2) + 1 : 1);
        }
        map1.forEach((k, v) -> {
            if (map2.containsKey(k))
                map3.put(k, v <= map2.get(k) ? v : map2.get(k));
        });
        int num = 0;
        Collection<Integer> values = map3.values();
        for (int n : values) {
            num += n;
        }
        int[] ret = new int[num];
        int j = 0;
//        map3.forEach((k, v) -> {
//            for (int i = 0; i < v; i++) {
//                ret[j++] = k;
//            }
//        });
        return ret;
    }
}
